<template>
    <div>
        <div class="treeTableTemp">
            <el-table
                :data="dataSource"
                style="width: 100%; margin-bottom: 20px"
                row-key="id"
                height="450"
                border
                show
                :default-expand-all="false"
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            >
                <el-table-column prop="title" label="系统-菜单" width="300"> </el-table-column>
                <el-table-column prop="searchTitle" label="勾选">
                    <template slot-scope="scope">
                        <el-checkbox
                            style="cursor: pointer"
                            v-model="scope.row.checked"
                            size="medium"
                            @change="
                                (e) => {
                                    changeCheck(e, scope.row)
                                }
                            "
                        ></el-checkbox>
                    </template>
                </el-table-column>
                <el-table-column prop="searchTitle" label="查询">
                    <template slot-scope="scope">
                        <el-switch
                            style="cursor: pointer"
                            v-model="scope.row.searchCheck"
                            @change="
                                (e) => {
                                    searchChange(e, scope.row)
                                }
                            "
                        >
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column prop="addTitle" label="添加">
                    <template slot-scope="scope">
                        <el-switch
                            style="cursor: pointer"
                            v-model="scope.row.addCheck"
                            @change="
                                (e) => {
                                    addChange(e, scope.row)
                                }
                            "
                        >
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column prop="editTitle" label="修改">
                    <template slot-scope="scope">
                        <el-switch
                            style="cursor: pointer"
                            v-model="scope.row.editCheck"
                            @change="
                                (e) => {
                                    editChange(e, scope.row)
                                }
                            "
                        >
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column prop="deleteTitle" label="删除">
                    <template slot-scope="scope">
                        <el-switch
                            style="cursor: pointer"
                            v-model="scope.row.deleteCheck"
                            @change="
                                (e) => {
                                    deleteChange(e, scope.row)
                                }
                            "
                        >
                        </el-switch> </template
                ></el-table-column>
                <el-table-column prop="instructionTitle" label="指令下发">
                    <template slot-scope="scope">
                        <el-switch
                            style="cursor: pointer"
                            v-model="scope.row.instructionCheck"
                            @change="
                                (e) => {
                                    instructionChange(e, scope.row)
                                }
                            "
                        >
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column prop="checkTitle" label="审核">
                    <template slot-scope="scope">
                        <el-switch
                            style="cursor: pointer"
                            v-model="scope.row.ckCheck"
                            @change="
                                (e) => {
                                    ckChange(e, scope.row)
                                }
                            "
                        >
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column prop="downloadTitle" label="下载">
                    <template slot-scope="scope">
                        <el-switch
                            style="cursor: pointer"
                            v-model="scope.row.downloadCheck"
                            @change="
                                (e) => {
                                    downloadChange(e, scope.row)
                                }
                            "
                        >
                        </el-switch> </template
                ></el-table-column>
            </el-table>
        </div>
        <div style="text-align: right; margin-top: 10px">
            <Button type="primary" style="margin-right: 10px" @click="saveData">确定</Button>
            <Button type="primary" @click="cancel">取消</Button>
        </div>
    </div>
</template>

<script>
import customDialog from '@/components/customComponents/customDialog'
import {AjaxCommon} from '@/libs/apiCommon'
import {PopupCommon} from '@/libs/popupCommon'
import {Utility} from '@/libs/utility'
export default {
    props: ['roleItem', 'rolePower'],
    components: {
        customDialog
    },
    data() {
        return {
            MENUS_GUID: '',
            SYS_GUIDS: [],
            selectRoleItem: [],
            secondTableHeight: 350,
            dataSource: []
        }
    },
    created() {
        this.selectRoleItem = this.roleItem
    },
    methods: {
        changeCheckData(isTrue, newData) {
            if (newData.children && newData?.children?.length > 0) {
                newData.children.map((item) => {
                    item.checked = isTrue
                    this.changeCheckData(isTrue, item)
                })
            }
        },
        changeCheck(e, row) {
            // this.changeCheckData(e, row)
            this.changeSwitchData(e, row, 'checked')
        },
        // 查找父节点
        findParentNode(nodes, childId) {
            for (const node of nodes) {
                if (node.children && node.children.some((child) => child.id === childId)) {
                    return node
                }

                if (node.children && node.children.length > 0) {
                    const found = this.findParentNode(node.children, childId)
                    if (found) return found
                }
            }
            return null
        },
        // 更新父节点状态
        updateParentNode(childNode, type) {
            // 找到父节点
            const parentNode = this.findParentNode(this.dataSource, childNode.id)
            if (!parentNode) return

            // 检查所有子节点是否都被选中
            let allChildrenChecked = null
            let checkedValue = ''
            if (type == 'search') {
                allChildrenChecked = parentNode.children.every((child) => child.searchCheck)
                checkedValue = 'searchCheck'
            }
            if (type == 'add') {
                allChildrenChecked = parentNode.children.every((child) => child.addCheck)
                checkedValue = 'addCheck'
            }
            if (type == 'edit') {
                allChildrenChecked = parentNode.children.every((child) => child.editCheck)
                checkedValue = 'editCheck'
            }
            if (type == 'delete') {
                allChildrenChecked = parentNode.children.every((child) => child.deleteCheck)
                checkedValue = 'deleteCheck'
            }
            if (type == 'instruction') {
                allChildrenChecked = parentNode.children.every((child) => child.instructionCheck)
                checkedValue = 'instructionCheck'
            }
            if (type == 'ck') {
                allChildrenChecked = parentNode.children.every((child) => child.ckCheck)
                checkedValue = 'ckCheck'
            }
            if (type == 'download') {
                allChildrenChecked = parentNode.children.every((child) => child.downloadCheck)
                checkedValue = 'downloadCheck'
            }
            if (type == 'checked') {
                allChildrenChecked = parentNode.children.every((child) => child.checked)
                checkedValue = 'checked'
            }

            // 如果状态有变化，更新父节点并递归检查上一级
            if (parentNode[checkedValue] !== allChildrenChecked) {
                parentNode[checkedValue] = allChildrenChecked
                this.updateParentNode(parentNode, type)
            }
        },
        // 更新父节点的选中状态
        toggleNode(isTrue, node, type) {
            // node.checked = isTrue
            // 如果有子节点，同步设置子节点状态
            if (node.children && node.children.length > 0) {
                node.children.map((t) => {
                    if (type == 'search') {
                        t.searchCheck = isTrue
                    }
                    if (type == 'add') {
                        t.addCheck = isTrue
                    }
                    if (type == 'edit') {
                        t.editCheck = isTrue
                    }
                    if (type == 'delete') {
                        t.deleteCheck = isTrue
                    }
                    if (type == 'instruction') {
                        t.instructionCheck = isTrue
                    }
                    if (type == 'ck') {
                        t.ckCheck = isTrue
                    }
                    if (type == 'download') {
                        t.downloadCheck = isTrue
                    }
                    if (type == 'checked') {
                        t.checked = isTrue
                    }
                    this.toggleNode(isTrue, t, type)
                })
            } else {
                // 如果是叶子节点，检查父节点是否需要更新
                this.updateParentNode(node, type)
            }
        },

        // 更新子节点的选中状态
        changeSwitchData(isTrue, newData, type) {
            this.toggleNode(isTrue, newData, type)
        },
        searchChange(e, item) {
            this.changeSwitchData(e, item, 'search')
        },
        cancel() {
            let self = this
            PopupCommon.confirm('确定要取消当前操作吗？取消后当前编辑数据将丢失！')
                .then((result) => {
                    if (result) {
                        self.$emit('cancel', '')
                    }
                })
                .catch((err) => {
                    console.log(err)
                })
        },
        menuDeal(item, id) {
            if (item?.children && item.children.length > 0) {
                item.children.map((menu) => {
                    if (menu.checked && (this.SYS_GUIDS.length == 0 || !this.SYS_GUIDS.includes(id))) {
                        this.SYS_GUIDS.push(id)
                    }
                    if (menu.checked) {
                        // 菜单 多个菜单ID用，分隔  菜单和按钮用$分隔）
                        /// 菜单返回 中men的GUID及按钮操作集合（多个菜单ID用，分隔  菜单和按钮用$分隔）
                        /// 示例 00701f90-f097-4e42-a69a-a42c3bc97e86$0|0|0|0|0|0|0,04c3e890-36b2-46bc-af83-e1b28801aca8$1|0|0|0|0|0|0
                        this.MENUS_GUID += `${menu.id}$${menu.searchCheck ? 1 : 0}|${menu.addCheck ? 1 : 0}|${menu.editCheck ? 1 : 0}|${
                            menu.deleteCheck ? 1 : 0
                        }|${menu.instructionCheck ? 1 : 0}|${menu.ckCheck ? 1 : 0}|${menu.downloadCheck ? 1 : 0},`
                        this.menuDeal(menu, id)
                    } else {
                        this.menuDeal(menu, id)
                    }
                })
            }
        },
        async saveData() {
            const dataSource = this.dataSource
            // 子系统id，以逗号隔开
            this.SYS_GUIDS = []
            // 菜单 多个菜单ID用，分隔  菜单和按钮用$分隔）
            /// 菜单返回 中men的GUID及按钮操作集合（多个菜单ID用，分隔  菜单和按钮用$分隔）
            /// 示例 00701f90-f097-4e42-a69a-a42c3bc97e86$0|0|0|0|0|0|0,04c3e890-36b2-46bc-af83-e1b28801aca8$1|0|0|0|0|0|0
            this.MENUS_GUID = ''
            dataSource?.forEach((p) => {
                if (p.attributes == 'sys') {
                    this.menuDeal(p, p.id)
                }
            })
            let MENUS_GUID = this.MENUS_GUID

            if (this.SYS_GUIDS.length == 0) {
                PopupCommon.notify('info', '请至少选择一个子系统')
                return
            }
            if (MENUS_GUID == '') {
                PopupCommon.notify('info', '请至少选择一个菜单和按钮')
                return
            }

            const SYS_GUIDS = this.SYS_GUIDS.toString()

            MENUS_GUID = MENUS_GUID.substring(0, MENUS_GUID.length - 1)
            const roleItem = this.selectRoleItem
            const params = {
                ROLE_NAME: roleItem.ROLE_NAME,
                PARENT_ROLE_NAME: roleItem.PARENT_ROLE_NAME,
                MENUS_GUID,
                // 子系统id
                SYS_GUIDS
            }
            const res = await AjaxCommon(`/api/Role/EditRoleMenu`, 'post', params)
            if (res?.data?.Code == 200) {
                PopupCommon.notify('success', '保存成功')
                this.$emit('onSave', '""')
            } else {
                PopupCommon.notify('error', res?.data?.msg)
            }
        },
        checkTreeData(type, newData) {
            if (newData.children && newData?.children?.length > 0) {
                newData.children.map((item) => {
                    if (type == 'search') {
                        item.searchCheck = newData.searchCheck
                    }
                    if (type == 'add') {
                        item.addCheck = newData.addCheck
                    }
                    if (type == 'edit') {
                        item.editCheck = newData.editCheck
                    }
                    if (type == 'delete') {
                        item.deleteCheck = newData.deleteCheck
                    }
                    if (type == 'instruction') {
                        item.instructionCheck = newData.instructionCheck
                    }
                    if (type == 'ck') {
                        item.ckCheck = newData.ckCheck
                    }
                    if (type == 'download') {
                        item.downloadCheck = newData.downloadCheck
                    }
                    if (item?.children?.length > 0) {
                        this.checkTreeData(type, item)
                    }
                })
            }
        },
        setChange(item, type) {
            this.dataSource.map((t) => {
                if (t.id == item.id) {
                    if (type == 'search') {
                        t.searchCheck = item.searchCheck
                    }
                    if (type == 'add') {
                        t.addCheck = item.addCheck
                    }
                    if (type == 'edit') {
                        t.editCheck = item.editCheck
                    }
                    if (type == 'delete') {
                        t.deleteCheck = item.deleteCheck
                    }
                    if (type == 'instruction') {
                        t.instructionCheck = item.instructionCheck
                    }
                    if (type == 'ck') {
                        t.ckCheck = item.ckCheck
                    }
                    if (type == 'download') {
                        t.downloadCheck = item.downloadCheck
                    }
                    this.checkTreeData(type, t)
                } else {
                    if (t.children && t.children.length > 0) {
                        t.children.map((a) => {
                            if (a.id == item.id) {
                                if (type == 'search') {
                                    a.searchCheck = item.searchCheck
                                }
                                if (type == 'add') {
                                    a.addCheck = item.addCheck
                                }
                                if (type == 'edit') {
                                    a.editCheck = item.editCheck
                                }
                                if (type == 'delete') {
                                    a.deleteCheck = item.deleteCheck
                                }
                                if (type == 'instruction') {
                                    a.instructionCheck = item.instructionCheck
                                }
                                if (type == 'ck') {
                                    a.ckCheck = item.ckCheck
                                }
                                if (type == 'download') {
                                    a.downloadCheck = item.downloadCheck
                                }

                                this.checkTreeData(type, a)
                            } else {
                                if (a.children && a.children.length > 0) {
                                    a.children.map((b) => {
                                        if (b.id == item.id) {
                                            if (type == 'search') {
                                                b.searchCheck = item.searchCheck
                                            }
                                            if (type == 'add') {
                                                b.addCheck = item.addCheck
                                            }
                                            if (type == 'edit') {
                                                b.editCheck = item.editCheck
                                            }
                                            if (type == 'delete') {
                                                b.deleteCheck = item.deleteCheck
                                            }
                                            if (type == 'instruction') {
                                                b.instructionCheck = item.instructionCheck
                                            }
                                            if (type == 'ck') {
                                                b.ckCheck = item.ckCheck
                                            }
                                            if (type == 'download') {
                                                b.downloadCheck = item.downloadCheck
                                            }
                                            this.checkTreeData(type, b)
                                        }
                                    })
                                }
                            }
                        })
                    }
                }
                return t
            })
        },
        addChange(e, item) {
            this.changeSwitchData(e, item, 'add')
        },
        editChange(e, item) {
            this.changeSwitchData(e, item, 'edit')
        },
        deleteChange(e, item) {
            this.changeSwitchData(e, item, 'delete')
        },
        instructionChange(e, item) {
            this.changeSwitchData(e, item, 'instruction')
        },
        ckChange(e, item) {
            this.changeSwitchData(e, item, 'ck')
        },
        downloadChange(e, item) {
            this.changeSwitchData(e, item, 'download')
        },
        getHeight() {
            this.secondTableHeight = 350
        },
        // 初始化事件
        async initPage() {
            // 获取所有的子系统+菜单
            const allData = await AjaxCommon(`/api/role/GetMenuTree`, 'get', null)
            let listData = allData?.data?.Message ?? []
            let treeDataList = []
            const rolePower = this.rolePower
            let powerListId = []
            let listPower = []

            // 拿到所有子级
            let childrenList = []
            if (rolePower && rolePower.length > 0) {
                // 拉平
                listPower = Utility.arrayFlat(rolePower, (t) => t.children)
                childrenList = listPower.filter((t) => typeof t.children == 'undefined')
                // powerListId = listPower.filter((t) => typeof t.checked == 'undefined' || t.checked)?.map((t) => t.id) ?? []
                powerListId = listPower.filter((t) => t.checked)?.map((t) => t.id) ?? []
            }
            Utility.createRoleMenuTreeData(listData, treeDataList, powerListId, listPower)
            this.dataSource = treeDataList

            if (childrenList.length > 0) {
                childrenList.map((t) => {
                    this.updateParentNode(t, 'search')
                    this.updateParentNode(t, 'add')
                    this.updateParentNode(t, 'edit')
                    this.updateParentNode(t, 'delete')
                    this.updateParentNode(t, 'instruction')
                    this.updateParentNode(t, 'ck')
                    this.updateParentNode(t, 'download')
                    this.updateParentNode(t, 'checked')
                })
            }
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.getHeight()
            this.initPage()
        })

        /*窗口自适应，关键代码*/
        window.onresize = () => {
            this.getHeight()
        }
    }
}
</script>

<style lang="scss">
.treeTableTemp {
    font-size: 14px;
    .zk-table {
        font-size: 14px !important;
        font-family: 'Microsoft YaHei', 微软雅黑, sans-serif;
    }

    .el-checkbox__inner {
        width: 20px;
        height: 20px;
        &::after {
            left: 5px;
            width: 6px;
            top: 3px;
            cursor: pointer;
        }
    }
}
</style>
